<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Tools, MapLocation, Van, Warning, Document, Location, Timer, CircleCheck } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage } from 'element-plus'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'

const router = useRouter()
const userStore = useUserStore()
const currentUser = userStore.userInfo.username

// 养护任务列表
const maintenanceTasks = ref([])
const loading = ref(true)

// 加载养护任务
const loadMaintenanceTasks = async () => {
  loading.value = true
  try {
    // 创建道路损坏要素图层
    const roadDamageLayer = new FeatureLayer({
      url: 'https://services7.arcgis.com/gcgG56UMRGbwuqfF/arcgis/rest/services/RoadDamageSegment/FeatureServer/0',
      outFields: ['*']
    })

    // 查询分配给当前养护人员的道路损坏数据
    const query = roadDamageLayer.createQuery()
    query.where = `maintainer = '${currentUser}' OR maintainer IS NULL` // 查询分配给当前用户的数据或未分配的数据
    query.outFields = ["*"]
    query.returnGeometry = false

    const results = await roadDamageLayer.queryFeatures(query)
    const features = results.features

    // 转换为任务列表格式
    maintenanceTasks.value = features
      .filter(feature => feature.attributes.status !== '已完成') // 只显示未完成的任务
      .map(feature => {
        // 根据严重程度设置优先级
        let priority = 'medium'
        if (feature.attributes.severityLevel === '严重' || feature.attributes.severityLevel === '危险') {
          priority = 'high'
        } else if (feature.attributes.severityLevel === '轻微') {
          priority = 'low'
        }

        // 设置状态
        let status = 'pending'
        if (feature.attributes.status === '处理中') {
          status = 'in-progress'
        }

        // 计算截止日期（默认为报告日期后15天）
        const reportDate = feature.attributes.reportTime ? new Date(feature.attributes.reportTime) : new Date()
        const deadline = new Date(reportDate)
        deadline.setDate(deadline.getDate() + 15)

        return {
          id: feature.attributes.OBJECTID,
          title: feature.attributes.damageType || '道路损坏',
          location: feature.attributes.roadName || '未知位置',
          priority: priority,
          status: status,
          deadline: deadline.toLocaleDateString(),
          description: feature.attributes.description || ''
        }
      })

    loading.value = false
  } catch (error) {
    console.error('加载养护任务失败', error)
    ElMessage.error('加载养护任务失败')
    loading.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  loadMaintenanceTasks()
})

// 获取任务优先级对应的标签类型
const getPriorityTag = (priority: string) => {
  switch (priority) {
    case 'high':
      return 'danger'
    case 'medium':
      return 'warning'
    case 'low':
      return 'info'
    default:
      return ''
  }
}

// 获取任务状态对应的标签类型和文本
const getStatusInfo = (status: string) => {
  switch (status) {
    case 'pending':
      return { type: 'info', text: '待处理' }
    case 'in-progress':
      return { type: 'warning', text: '进行中' }
    case 'completed':
      return { type: 'success', text: '已完成' }
    default:
      return { type: '', text: '' }
  }
}

// 获取优先级对应的文本
const getPriorityText = (priority: string) => {
  switch (priority) {
    case 'high':
      return '高'
    case 'medium':
      return '中'
    case 'low':
      return '低'
    default:
      return ''
  }
}

// 表格行样式
const tableRowClassName = ({ row }: { row: any }) => {
  if (row.priority === 'high') {
    return 'high-priority-row'
  }
  return ''
}
</script>

<template>
  <div class="maintainer-container">
    <!-- 快速操作按钮 -->
    <el-row :gutter="20" class="action-row">
      <el-col :span="24">
        <el-card class="action-card">
          <div class="action-buttons">
            <el-button type="primary" @click="router.push('/maintenance/road-damage')">
              <el-icon><Warning /></el-icon> 道路损坏处理
            </el-button>
            <el-button type="success" @click="router.push('/maintenance/reports')">
              <el-icon><Document /></el-icon> 工作报告
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="16">
        <el-card class="task-list-card">
          <template #header>
            <div class="card-header">
              <el-icon><Tools /></el-icon>
              <span>待处理养护任务</span>
            </div>
          </template>

          <el-table v-loading="loading" :data="maintenanceTasks" style="width: 100%" :row-class-name="tableRowClassName">
            <el-table-column prop="id" label="任务ID" width="80" />
            <el-table-column prop="title" label="任务名称" width="150" />
            <el-table-column prop="location" label="位置">
              <template #default="scope">
                <div class="location-cell">
                  <el-icon><Location /></el-icon>
                  <span>{{ scope.row.location }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="priority" label="优先级" width="100">
              <template #default="scope">
                <el-tag :type="getPriorityTag(scope.row.priority)" effect="dark" size="small">
                  {{ getPriorityText(scope.row.priority) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusInfo(scope.row.status).type" size="small">
                  {{ getStatusInfo(scope.row.status).text }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="deadline" label="截止日期" width="120">
              <template #default="scope">
                <div class="deadline-cell">
                  <el-icon><Timer /></el-icon>
                  <span>{{ scope.row.deadline }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button size="small" type="primary" plain @click="router.push(`/maintenance/road-damage?id=${scope.row.id}`)">处理</el-button>
                <el-button size="small" type="info" plain>详情</el-button>
              </template>
            </el-table-column>
            <template #empty>
              <el-empty v-if="!loading" description="暂无养护任务" />
            </template>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
.maintainer-container {
  padding: 20px;
}

.action-row {
  margin-bottom: 20px;
}

.action-card {
  padding: 10px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.card-header {
  display: flex;
  align-items: center;
  font-weight: bold;
}

.card-header .el-icon {
  margin-right: 10px;
  font-size: 18px;
}

.task-list-card, .completed-tasks-card, .quick-actions-card {
  margin-bottom: 20px;
}

.map-card {
  margin-bottom: 20px;
  height: 300px;
}

.equipment-card {
  margin-bottom: 20px;
}

.map-placeholder {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
}

.map-icon {
  width: 80px;
  height: 80px;
}

.location-cell, .deadline-cell, .date-cell {
  display: flex;
  align-items: center;
}

.location-cell .el-icon, .deadline-cell .el-icon, .date-cell .el-icon {
  margin-right: 5px;
  font-size: 14px;
}

.high-priority-row {
  background-color: rgba(245, 108, 108, 0.1);
}

.action-card {
  cursor: pointer;
  transition: all 0.3s;
}

.action-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.action-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 15px 0;
}

.action-content .el-icon {
  font-size: 24px;
  margin-bottom: 10px;
  color: #409EFF;
}
</style>
